<?php
// 图片管理模块
class PhotoAction extends CommonAction {
	public function _before_update() {
		$this->_before_insert(1);
	}
	//添加图片
	public function _before_insert($isupdate=0) {
		if(!empty($_FILES['img']['name'])){
			import("ORG.Net.UploadFile");
			$upload = new UploadFile();
			$upload->maxSize  = 1048576 * 3 ; 
			$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');
			$upload->savePath =  './Public/Upload/photo/';
			$upload->saveRule = 'uniqid';
			$upload->thumb = true;
			$upload->thumbMaxWidth = 100;
			$upload->thumbMaxHeight = 100;
			$upload->uploadReplace = false;
			$upload->thumbPrefix = '100_100_';
			if(!$upload->upload()) { 
				$this->error($upload->getErrorMsg());
			}else{
				//删除旧文件
				if(!$isupdate){
					$oldfile = M('Photo')->where(is_numeric($_POST['id']) ? $_POST['id'] : M('Photo')->getLastInsID())->getField('img');
					$oldfile = $_SERVER['DOCUMENT_ROOT'].chimg($oldfile,'photo');
					if(is_file($oldfile)) unlink($oldfile);
				}
				$imgs = $upload->getUploadFileInfo();
				$_POST['img'] = $imgs[0]['savename'];				
				echo 
				'<script type="text/javascript">
				var response = {
					"status":"1",
					"info":"\u64cd\u4f5c\u6210\u529f",
					"navTabId":"Photo",
					"forwardUrl":"",
					"callbackType":"closeCurrent"
				};
				if(window.parent.donecallback) {
					 window.parent.donecallback(response);
				}
			   </script>';
			}
		}
	}
	
	//删除测试时删除预览图片,删除路由规则
	public function _before_foreverdelete() {
		$ids = $this->_beforDelFiles(MODULE_NAME);
		if($ids){
			$list = M(MODULE_NAME)->where( array(M(MODULE_NAME)->getPk()=>array('in', $ids)) )->field('rewrite')->select();
			foreach($list as $rs) $rewrite .= ($rewrite ? "','" : '') . $rs['rewrite'];
			if($rewrite) M('Router')->where( "rewrite in ('{$rewrite}')" )->delete();
		}
	}
}